package com.example.gokuplayalong.service.home;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.security.MD5Keys;
import com.example.gokuplayalong.bases.network.security.MD5Util;
import com.example.gokuplayalong.bases.network.updown.DownLoad;
import com.example.gokuplayalong.bases.tools.Logger;
import com.example.gokuplayalong.bases.upgrade.UpgradeHistory;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeShow#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeShow extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    try {
                        checkLoginState();

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
            }
        }
    };

    public HomeShow() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeShow.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeShow newInstance(String param1, String param2) {
        HomeShow fragment = new HomeShow();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_home_show, container, false);
        initView();
        return rootView;
    }

    private void initView() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {

        try {

//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    try {
//
//                        SysManagerFragments.switchOnSysFragmentThree("HomeMain");
//                    } catch (Throwable e) {
//
//                    }
//                }
//            }, 1000);

            checkLoginState();

        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void checkLoginState() {

        try {


            File f = new File(AppParams.getInstance().mediaDir, "versioninfo");

            if (f.exists()) {
                InputStreamReader inputStreamReader = new InputStreamReader(Files.newInputStream(f.toPath()));
                BufferedReader bf = new BufferedReader(inputStreamReader);
                String str;

                while ((str = bf.readLine()) != null) {
                    if (DownLoad.getVersionName().compareTo(str) > 0) {
                        //升级后的初始化操作
                        UpgradeHistory.getInstance().init();
                    }
                }
            }
            f = new File(AppParams.getInstance().mediaDir, "versioninfo");
            FileWriter fileWriter = new FileWriter(f.getAbsoluteFile(), false);
            fileWriter.write(DownLoad.getVersionName());
            fileWriter.close();

            AppParams.getInstance().appCurrentUser.getJsonObject().put("Flag", 0);
            f = new File(AppParams.getInstance().mediaDir, "currentuser.txt");
            if (f.exists()) {
                InputStreamReader inputStreamReader = new InputStreamReader(Files.newInputStream(f.toPath()));
                BufferedReader bf = new BufferedReader(inputStreamReader);
                String str;
                String[] strings;
                String[] strings1;
                while ((str = bf.readLine()) != null) {
                    strings = str.split("\\.");
                    String strT = new String(Base64.getDecoder().decode(strings[0].getBytes()));
                    strings1 = strT.split("#");
                    String md5 = MD5Util.string2MD5(strings[0] + MD5Keys.getInstance().getKey());
                    if (Objects.equals(md5, strings[1])) {
                        Logger.d(Arrays.toString(strings1));
                        AppParams.getInstance().appCurrentUser.getJsonObject().put("phone", strings1[0]);
                        AppParams.getInstance().appCurrentUser.getJsonObject().put("userid", strings1[1]);
                        AppParams.getInstance().appCurrentUser.getJsonObject().put("lastonlinetime", strings1[2]);
                        AppParams.getInstance().appCurrentUser.getJsonObject().put("token", strings1[3]);
                        AppParams.getInstance().appCurrentUser.getJsonObject().put("Flag", 1);
                    }
                }
            }
            if (StringUtils.isEmpty(AppParams.getInstance().appCurrentUser.getJsonObject().getString("token"))) {
                AppParams.getInstance().appCurrentUser.getJsonObject().put("Flag", 0);
            }

            if (AppParams.getInstance().appCurrentUser.getJsonObject().getIntValue("Flag") == 0) {

                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {

                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SysManagerFragments.switchOnSysFragmentThree("HomeLogin");
                                cancel();
                            }
                        });
                        cancel();
                    }
                }, 200, 1);

            }
            else {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {

                        requireActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SysManagerFragments.switchOnSysFragmentThree("HomeMain");
                                cancel();
                            }
                        });
                        cancel();
                    }
                }, 200, 1);
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

}